package com.example.myblog01.web.admin;

import com.example.myblog01.pojo.User;
import com.example.myblog01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;


    @GetMapping
    public String loginpage(){
        return "admin/login";
    }

    @PostMapping("/login")//RequestParam接收前端参数
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
//                        RedirectAttributes attributes用来存放提示信息
                        RedirectAttributes attributes){

        User user = userService.chickUser(username,password);
        if(user != null){
            user.setPassword(null);//前端拿到密码后设置成空
//            setAttribute往session添加信息
            session.setAttribute("user",user);
            return "admin/index";
        }else {
            attributes.addFlashAttribute("message","用户名和密码错误");
            return "redirect:/admin";
        }
    }




    @GetMapping("/logout")
    public String logout(HttpSession session){
//        移除removeAttribute信息
        session.removeAttribute("user");
        return "redirect:/admin";
    }

}
